package com.oscar.ehome.view.pageview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.oscar.ehome.MainActivity;
import com.oscar.ehome.R;
import com.oscar.ehome.base.AppManager;
import com.oscar.ehome.base.C;
import com.oscar.ehome.base.activity.BaseActivity;
import com.oscar.ehome.bean.pagebean.StudyDetialBean;
import com.oscar.ehome.presenter.PagePresenter;
import com.oscar.ehome.provider.gildeimage.GildeUtils;
import com.oscar.ehome.provider.videoPlay.NiceVideoPlayerManagers;
import com.oscar.ehome.provider.videoPlay.NiceVideoPlayers;
import com.oscar.ehome.provider.videoPlay.TxVideoPlayerControllers;
import com.oscar.ehome.utils.basethem.TintManager;
import com.oscar.ehome.utils.database.DataBaseDAO;
import com.oscar.ehome.utils.dowload.dowload.DownloadManager;
import com.oscar.ehome.utils.dowload.dowload.OnDownload;
import com.oscar.ehome.utils.dowload.entity.FileInfo;
import com.oscar.ehome.utils.dowload.progressbar.RoundProgressBar;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.SystemBarTintManager;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.util.makeTime;
import com.oscar.ehome.utils.view.progressview.ProgressFrameLayout;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.pageview.view.StudyDetialView;
import com.xiao.nicevideoplayer.NiceVideoPlayer;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by oscar
 * author: MengWanhe
 * date: On 2017/7/10
 * 视频播放
 */

public class VideoActivity extends BaseActivity implements StudyDetialView, TxVideoPlayerControllers.SetFullScreenListener,
        ProgressFrameLayout.AgainRequestListener, NiceVideoPlayers.NiceCallBack, TxVideoPlayerControllers.SetNotFullScreenListener {

    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     * 播放视频
     */
    @BindView(R.id.detail_player)
    NiceVideoPlayers detailPlayer;
    /**
     * 标题
     */
    @BindView(R.id.video_title)
    TextView videoTitle;
    /**
     * 作者
     */
    @BindView(R.id.video_author)
    TextView videoAuthor;
    /**
     * 时间
     */
    @BindView(R.id.video_time)
    TextView videoTime;
    /**
     * 下载
     */
    static ImageView videoDownload;
    /**
     * 内容
     */
    @BindView(R.id.video_content)
    TextView videoContent;
    /**
     * 布局
     */
    @BindView(R.id.linearlayout_video)
    LinearLayout linearlayoutVideo;
    /**
     * 进度条
     */
    static RoundProgressBar roundProgressBar;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;

    @BindView(R.id.videos_fragment)
    FrameLayout videosFragment;

    @BindView(R.id.video_fragment)
    ProgressFrameLayout videoFragment;
    @BindView(R.id.home_tv_num)
    TextView title_tv_right;
    public String id = "";
    public String token = "";
    public PagePresenter pagePresenter;


    /**
     * 下载的文件详情
     */
    public FileInfo info;
    private TimeCount timeCount;
    public String title = "";
    public String videoUrl = "";//下载地址
    public String fileName = "";//文件名字
    public static String ids = "";//文件ID
    public static String voideo_id = "";//文件ID
    public int dowload = 0;//下载状态
    public String localPath = "";//文件存放路径
    String startime = "";//开始时间
    String endtime = "", type = "";//结束时间
    String time = "";//秒数
    int fin = 0;//是否关闭页面
    String imgdata;//存入数据库的图片
    SystemBarTintManager tintManager;
    /* 标记当视频暂停时播放位置 */
    private long intPositionWhenPause = -1;
    TxVideoPlayerControllers controller;

    DataBaseDAO dataBaseDAO;//数据库

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);
        setBaseBackground(VideoActivity.this);
        ButterKnife.bind(this);

        setColor();
        initView();
        setVideo();
        initData();
    }

    /**
     * 设置颜色
     */
    public void setColor() {
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(VideoActivity.this).getSystemConfig().getColor()));
    }
    /**
     * 倒计时
     */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {//计时完毕时触发
            title_tv_right.setText("完成");
            title_tv_right.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            title_tv_right.setClickable(false);
            title_tv_right.setText("完成("+millisUntilFinished / 1000 + "秒)");
        }
    }


    /**
     * 初始化
     */
    public void initView() {

        roundProgressBar = (RoundProgressBar) findViewById(R.id.roundProgressBar);
        videoDownload = (ImageView) findViewById(R.id.video_download);
        Intent in = getIntent();
        if (in.getStringExtra("type") != null && in.getStringExtra("type").equals("qiangzhi")) {
            type = in.getStringExtra("type");
            titleImgBack.setVisibility(View.GONE);
            title_tv_right.setVisibility(View.VISIBLE);
            timeCount = new TimeCount(60000, 1000);
            timeCount.start();
        } else {
            title_tv_right.setVisibility(View.GONE);
            titleImgBack.setVisibility(View.VISIBLE);
            titleImgBack.setImageResource(R.mipmap.fanhui);
        }


        titleTopbar.setText("视频");
        id = getIntent().getStringExtra("id");
        token = SystemConfigFactory.getInstance(VideoActivity.this).getSystemConfig().getToken();
        startime = makeTime.mtime();

        roundProgressBar.setVisibility(View.GONE);
      //  videoDownload.setVisibility(View.VISIBLE);
        localPath = CommonUtils.getSDCardRootPath(VideoActivity.this) + C.video;// 文件存储路径，sd卡路径

        pagePresenter = new PagePresenter(this);
        dataBaseDAO = new DataBaseDAO(VideoActivity.this);//创建数据库

        videoFragment.setAgainRequestListener(this);


    }

    /**
     * 下载的状态
     */

    public void undowload() {
        if (CommonUtils.GetVideoFileName(CommonUtils.getSDCardRootPath(VideoActivity.this) + C.video + fileName)) {// 已下载
            dowload = 1;
            videoDownload.setImageResource(R.mipmap.duigou);
            videoDownload.setEnabled(false);
            TintManager.setTint(videoDownload, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
            /* 这里更换视频播放地址 */

            detailPlayer.setUp(localPath + fileName, null);


            controller.setTitle(title);//这里设置视频的title
            Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(localPath + fileName
                    , MediaStore.Video.Thumbnails.MINI_KIND);//url的参数
            controller.imageView().setImageBitmap(bitmap);
            detailPlayer.setController(controller);

        } else {
            // 未下载
            dowload = 0;
             /* 这里更换视频播放地址 */

            detailPlayer.setUp(videoUrl, null);
            controller.setTitle("");//这里设置视频的title
            /* ?vframe/jpg/offset/0/w/500/h/500 视频第一帧拼接的字符串 */
            GildeUtils.loadUrlImages(videoUrl + "?vframe/jpg/offset/0/w/500/h/500", controller.imageView(), VideoActivity.this);
            detailPlayer.setController(controller);
            videoDownload.setImageResource(R.mipmap.xiazailiebiao);
            TintManager.setTint(videoDownload, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
        }
        if (CommonUtils.isVideo == 1) {
            if (voideo_id.equals(ids)) {
                dowload = 3;
               // roundProgressBar.setVisibility(View.VISIBLE);
                videoDownload.setVisibility(View.GONE);
            }
        }

        detailPlayer.setNiceCallBackClicksListener(this);

    }

    /**
     * 配置视频
     */
    public void setVideo() {

        detailPlayer.setPlayerType(NiceVideoPlayer.TYPE_NATIVE); // IjkPlayer or MediaPlayer
        controller = new TxVideoPlayerControllers(this);
        controller.setOnFullScreenClickListener(this);
        controller.setNotOnFullScreenClickListener(this);
    }

    /**
     * 加载数据
     */
    public void initData() {
        pagePresenter.getStudyDetial(token, id);
        showLoading();
    }

    /**
     * 加载数据
     */
    public void saveData() {
        fin = 2;
        time = makeTime.getDistanceTime(Long.parseLong(startime), Long.parseLong(endtime));
        pagePresenter.saveLearn(token, id, startime, endtime, time);
    }

    @OnClick({R.id.video_download, R.id.title_layout_left, R.id.roundProgressBar,R.id.home_tv_num})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.home_tv_num:
             if(title_tv_right.getText().equals("完成")){
                 if(dowload==4){
                     dowload_file();
                 }
                 if (videoUrl != null && !"".equals(videoUrl)) {
                     endtime = makeTime.mtime();
                     saveData();
                 } else {
                     Intent intent;
                     intent = new Intent(VideoActivity.this, MainActivity.class);
                     intent.putExtra("intent", 1);
                     startActivity(intent);
                     finish();
                 }
             }else{
                 ToastUtil.show(VideoActivity.this, "请倒计时结束后点击退出");
             }
                break;
            case R.id.title_layout_left:
                if(dowload==4){
                    dowload_file();
                }
                if (videoUrl != null && !"".equals(videoUrl)) {
                    endtime = makeTime.mtime();
                    saveData();
                } else {

                    finish();
                }
                break;
            case R.id.video_download://下载文件
                switch (dowload) {
                    case 0://未下载
                        dowload_file();
                        break;
                    case 1://已下载
                        ToastUtil.show(VideoActivity.this, R.string.dowload_file);
                        break;
                    case 3://正在下载，点击暂停
                        puseDowload_file();
                        break;
                    case 4://暂停中，点击继续下载
                        dowload_file();
                        break;
                }
                break;
            case R.id.roundProgressBar:
                switch (dowload) {
                    case 1://已下载
                        ToastUtil.show(VideoActivity.this, R.string.dowload_file);
                        break;
                    case 3://正在下载，点击暂停
                        puseDowload_file();
                        break;
                    case 4://暂停中，点击继续下载
                        dowload_file();
                        break;
                }
                break;
        }
    }


    /**
     * 下载文件的方法
     */
    public void dowload_file() {
        // 下载
        int info_id = 1;
      //  roundProgressBar.setVisibility(View.VISIBLE);
        videoDownload.setVisibility(View.GONE);

        info = new FileInfo(info_id, videoUrl, fileName, 0, 0);
        final OnDownloadImpl impl = new OnDownloadImpl(roundProgressBar, 0);
        DownloadManager.instance(VideoActivity.this).startDownload(info.getUrl(), localPath, fileName, impl,
                ids, roundProgressBar); // 开始下载
     //   ToastUtil.show(VideoActivity.this, "开始下载");

        dowload = 3;
    }

    /**
     * 暂停文件的方法
     */
    public void puseDowload_file() {
        dowload = 4;
        int info_id = 1;
        info = new FileInfo(info_id, videoUrl, 0, 0);
        DownloadManager.instance(VideoActivity.this).pauseDownload(info.getUrl());
        roundProgressBar.setVisibility(View.GONE);
       // videoDownload.setVisibility(View.VISIBLE);

        videoDownload.setImageResource(R.mipmap.zanting);
        TintManager.setTint(videoDownload, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
    }

    @Override
    public void againRequest() {

    }

    /**
     * 开始播放
     */
    @Override
    public void start() {

        if (dowload == 0) {
            dowload_file();
        }
    }

    @Override
    public void onNotFullScreenClick() {
        tintManager.setStatusBarTintColor(Color.parseColor(SystemConfigFactory.getInstance(VideoActivity.this).getSystemConfig().getColor()));
    }


    /**
     * 下载回调监听类
     */
    class OnDownloadImpl implements OnDownload {
        public RoundProgressBar pb; // 进度条
        public int position; // 列表位置

        public OnDownloadImpl(RoundProgressBar pb, int posision) {
            this.pb = pb;
            this.position = posision;
        }

        /**
         * 下载中
         */
        @Override
        public void onDownloading(String retUrl, int finished, String bookid, RoundProgressBar pb) {
            voideo_id = bookid;
            if (ids.equals(bookid)) {
                if (dowload == 3) {// 下载中
                    CommonUtils.isVideo = 1;
                    roundProgressBar.setProgress(finished);
                } else if (dowload == 4) {// 暂停
                    // 缓存的暂停的id和此文件的id相同的话点击此按钮直接继续下载,同时移除缓存的此文件id
                    roundProgressBar.setVisibility(View.GONE);
               //     videoDownload.setVisibility(View.VISIBLE);
                }
            }
        }

        /**
         * 下载完成
         */
        @Override
        public void onDownloadFinished(File downloadFile, int isfinshed) {
          //  ToastUtil.show(VideoActivity.this, "下载完成");
            roundProgressBar.setProgress(100);
            roundProgressBar.setVisibility(View.GONE);
        //    videoDownload.setVisibility(View.VISIBLE);
            videoDownload.setImageResource(R.mipmap.duigou);
            videoDownload.setEnabled(false);
            TintManager.setTint(videoDownload, Color.parseColor(SystemConfigFactory.getInstance(VideoActivity.this).getSystemConfig().getColor()));

            String sizes = CommonUtils.getFileOrFilesSize(localPath + fileName, 3);
            //插入数据库
            if (dowload != 1) {
                Map<String, Object> datas = new HashMap<String, Object>();// 存储
                datas.put("title", title);
                datas.put("imgdata", C.qiniu_ip + imgdata);
                datas.put("size", sizes);
                datas.put("filename", fileName);
                datas.put("learnType", "video/mp4");
                datas.put("ids", id);
                dataBaseDAO.insert("fileDownload", datas);
            }

            dowload = 1;
            CommonUtils.isVideo = 0;
        }

        /**
         * 是否连接网络
         */
        @Override
        public void onNetwork(boolean flag) {// 判断是否有网络
            // TODO Auto-generated method stub
            if (!flag) {// 无网络时
                // 暂停下载
                puseDowload_file();
            } else {// 暂停中 ，开始下载
                dowload_file();
            }
        }

        @Override
        public void onStrartDownloading(String url, String bookid) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onErroy(String bookid) {
            // TODO Auto-generated method stub
            if (ids.equals(bookid)) {
                ToastUtil.show(VideoActivity.this, "下载失败");
                roundProgressBar.setVisibility(View.GONE);
             //   videoDownload.setVisibility(View.VISIBLE);
                dowload = 0;
            }
        }
    }


    @Override
    public void getstudyDetail(StudyDetialBean result) {
        dismissLoading();

        if (result != null) {
            videoFragment.stopRefresh();
            videosFragment.setVisibility(View.VISIBLE);

            videoTitle.setText(result.getTitle());
            videoAuthor.setText(result.getCreateBy().getName());
            videoTime.setText(result.getUpdateDate());
            videoContent.setText(result.getRemarks());
            ids = result.getId();
            fileName = result.getMediaFile();
            videoUrl = C.qiniu_ip + result.getMediaFile();
            title = result.getTitle();
            imgdata = result.getSmallImg();
            String[] urls = {videoUrl};
            undowload();
        } else {
            videoFragment.setNoResult();

            videosFragment.setVisibility(View.GONE);
        }
    }

    /**
     * 保存学习记录
     *
     * @param result
     */
    @Override
    public void saveLearn(String result) {
        if (fin == 2) {
            if(type!=null&&type.equals("qiangzhi")){
                Intent intent;
                intent = new Intent(VideoActivity.this, MainActivity.class);
                intent.putExtra("intent", 1);
                startActivity(intent);
                finish();
            }else{
                finish();
            }

        }
    }

    @Override
    public void erroy() {
        dismissLoading();
        videoFragment.setNoResult();

        videosFragment.setVisibility(View.GONE);
        ToastUtil.show(VideoActivity.this, getString(R.string.erry));
        if (fin == 2) {
            finish();
        }
    }

    @Override
    public void erry(String result) {
        dismissLoading();
        videoFragment.setNoResult();

        videosFragment.setVisibility(View.GONE);
        Toast.makeText(VideoActivity.this, result, Toast.LENGTH_SHORT).show();
        if (result.contains("过期")) {
            getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(VideoActivity.this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(VideoActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        } else {
            if (fin == 2) {
                finish();
            }
        }
    }

    /**
     * 横屏处理
     */
    @Override
    public void onFullScreenClick() {//横屏
        tintManager.setStatusBarTintResource(R.color.transparent);
    }

    /**
     * 页面暂停效果处理
     */
    @Override
    protected void onPause() {
        super.onPause();
        if (detailPlayer.isPlaying()) {
            intPositionWhenPause = detailPlayer.getCurrentPosition();
            detailPlayer.pause();
        }
    }


    /* 这里处理再次进入页面从上次暂停的位置播放 */
    @Override
    protected void onResume() {
        super.onResume();
        if (intPositionWhenPause >= 0) {
            detailPlayer.seekTo(intPositionWhenPause);
            //初始播放位置
            intPositionWhenPause = -1;
        }
    }

    // 按下Home键暂停播放，回到界面继续播放。
    @Override
    protected void onStop() {
        NiceVideoPlayerManagers.instance().suspendNiceVideoPlayer();
        super.onStop();
    }

    @Override
    protected void onRestart() {
        NiceVideoPlayerManagers.instance().resumeNiceVideoPlayer();
        super.onRestart();
    }


    // 按返回键
    // 当前是全屏或小窗口，需要先退出全屏或小窗口。
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(type.equals("qiangzhi")){
                AppManager appManager = AppManager.getAppManager();
                appManager.finishAllActivity();
                finish();
            }else{
                if(dowload==4){
                    dowload_file();
                }
                if (!NiceVideoPlayerManagers.instance().onBackPressd()) {
                    endtime = makeTime.mtime();
                    if (videoUrl != null && !"".equals(videoUrl)) {
                        saveData();
                    } else {
                        finish();
                    }
                } else {
                    tintManager.setStatusBarTintColor(Color.parseColor(SystemConfigFactory.getInstance(VideoActivity.this).getSystemConfig().getColor()));
                }
            }

            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        // 很重要，在Activity和Fragment的onStop方法中一定要调用，释放的播放器。
        NiceVideoPlayerManagers.instance().releaseNiceVideoPlayer();
        if (!Util.isOnMainThread()) {
            Glide.with(VideoActivity.this).pauseRequests();
        }
        super.onDestroy();
    }

    /**
     * 设置系统标题背景颜色
     *
     * @param act
     */
    public void setBaseBackground(Activity act) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            CommonUtils.setTranslucentStatus(true, act);
            tintManager = new SystemBarTintManager(act);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintColor(Color.parseColor(SystemConfigFactory.getInstance(VideoActivity.this).getSystemConfig().getColor()));
        }
    }

}
